﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WisDom.IService;

namespace WisDom.Update.Controllers
{
    /// <summary>
    /// 文件管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class FileManagerController : ControllerBase
    {
        IHostingEnvironment environment; 
        public FileManagerController(IHostingEnvironment env)
        {
            this.environment = env; 
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost(Name ="UploadFile")]
        public IActionResult UploadFile()
        {
            // string fileName = "";
            string webPath = $"{environment.ContentRootPath}/upload/file/";
            if (System.IO.Directory.Exists(webPath) == false)
            {
                System.IO.Directory.CreateDirectory(webPath);
            }
            Dictionary<string, string> dicts = new Dictionary<string, string>();
            foreach (var file in Request.Form.Files)
            {
                string ext = System.IO.Path.GetExtension(file.FileName);
                string newFileName = Guid.NewGuid().ToString() + ext;
                var memoryStream = new MemoryStream();
                file.CopyTo(memoryStream);

                var fileStream = System.IO.File.Create($"{environment.ContentRootPath}/upload/file/{newFileName}", (int)file.Length, FileOptions.None);
                fileStream.Write(memoryStream.ToArray(), 0, (int)file.Length);

                fileStream.Flush();
                fileStream.Dispose();
                memoryStream.Flush();
                memoryStream.Dispose();

                dicts.Add(file.FileName, $"/upload/file/{newFileName}");
            }
            return new JsonResult(new { status = true, files = dicts });
        } 
       
    }
}